<script lang="ts" setup>
import {getPatientConsultOrderPreAPI, postPatientConsultOrderAPI, postPatientConsultPayAPI} from '@/apis/consult'
import {getPatientInfoByIdAPI} from '@/apis/patient'
import CustomPayment from '@/components/custom-payment/custom-payment.vue'
import {useConsultStore} from '@/stores/consult'
import type {GetPatientConsultOrderPreData} from '@/types/consult'
import type {CustomPaymentInstance} from '@/types/global-components'
import type {GetPatientMylistItem} from '@/types/patient'
import {customRef, onMounted, ref} from 'vue'

const store = useConsultStore()

// 1. 获取问诊预支付信息
const orderPreInfo = ref<GetPatientConsultOrderPreData>()
const getOrderPre = async () => {
  const res = await getPatientConsultOrderPreAPI({
    type: store.type,
    illnessType: store.illnessType,
  })
  orderPreInfo.value = res.data
}
getOrderPre()
const patientInfo = ref<GetPatientMylistItem>()
const getPatientInfo = async () => {
  const res = await getPatientInfoByIdAPI(store.patientId)
  patientInfo.value = res.data
}
getPatientInfo()
const orderId = ref('')
const handlePay = async() => {
  if (orderId.value){
return uni.showToast({
  title:'订单不能重复创建',
  icon:'none',
})
  }
  const res = await postPatientConsultOrderAPI({
    type:Number(store.type),
    illnessType:Number(store.illnessType),
    depId:store.depId,
    patientId:store.patientId,
    illnessDesc:store.illnessInfo.illnessDesc,
    illnessTime:store.illnessInfo.illnessTime,
    consultFlag:store.illnessInfo.consultFlag,
    pictures:store.illnessInfo.pictures, 
  })
  orderId.value = res.data.id
  // 清空 store 数据
  // store.reset()
  customPaymentRef.value?.open?.()
}

const customPaymentRef = ref<CustomPaymentInstance>()

onMounted(() => {
  // 检查暴露出来的方法
  console.log('暴露出来的方法', customPaymentRef.value)
})

const handleClose = async () => {
  // 二次确认提示
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  // 如果用户选择关闭，则关闭支付弹窗
  if (res.cancel) {
    customPaymentRef.value?.close?.()
  }
}
const handleConfirm =async (index: number) =>{
  if(index === 0) {
    uni.showToast({
      title:'微信支付暂不支持',
      icon:'none',
    })
     // #ifdef MP-WEIXIN
    // 本质还是发送网络请求，获取后端返回的参数
    // 调用微信支付的 API (SDK方法)
    // wx.requestPayment(传入后端返回的支付参数)
    // #endif
    } else if (index === 1) {
      // #ifndef MP-WEIXIN
    const res = await postPatientConsultPayAPI({
      orderId: orderId.value,
      paymentMethod: '1',
      // 支付完成，由支付宝打开问诊室页面，所以页面路径要完整，从 http 开始
      payCallback: 'http://localhost:5173/#/subpkg_consult/pages/room/room',
    })
    // 把地址栏的 url 重定向到支付宝支付付款页面
    location.href = res.data.payUrl
     // #endif
  }
}
const handleChange = (index: number) =>{
  console.log('切换支付方式',index);
  
}
</script>

<template>
  <scroll-view>
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
         :title="`图文问诊 ${orderPreInfo?.payment || '--'} 元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${orderPreInfo?.couponDeduction ?? ''}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">￥{{ orderPreInfo?.pointDeduction ?? '' }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">￥{{ orderPreInfo?.actualPayment ?? '' }}</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section title-font-size="32rpx" title-color="#121826" padding="30rpx" title="患者资料">
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
             <view class="uni-list-text-gray" v-if="patientInfo">
                {{ patientInfo?.name }} | {{ patientInfo?.genderValue }} | {{ patientInfo?.age }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" :note="store.illnessInfo.illnessDesc" />
        </uni-list>
      </uni-section>

      <!-- <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view> -->
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ orderPreInfo?.payment }}</text>
      </view>
      <button class="uni-button" @click="handlePay">立即支付</button>
    </view>
    <!-- 自定义支付弹窗 -->
    <custom-payment
      ref="customPaymentRef"
      :order-id="orderId"
      v-if="orderPreInfo?.payment"
      :amount="orderPreInfo?.payment"
      @close="handleClose"
      @confirm="handleConfirm"
      @change="handleChange"
    />
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';
</style>